<template>
  <div class="variable-selector">
    <el-popover
      v-model:visible="popoverVisible"
      placement="bottom"
      :width="300"
      trigger="click"
      popper-class="variable-popover"
    >
      <template #reference>
        <el-button 
          type="primary" 
          size="small" 
          plain
          class="variable-button"
          :disabled="disabled"
        >
          <el-icon><el-icon-magic-stick /></el-icon> 选择变量
        </el-button>
      </template>
      
      <div class="popover-content">
        <el-tabs v-model="activeTab" class="variable-tabs">
          <el-tab-pane label="全部变量" name="all"></el-tab-pane>
          <el-tab-pane label="全局变量" name="global"></el-tab-pane>
          <el-tab-pane label="局部变量" name="event"></el-tab-pane>
        </el-tabs>

        <el-input 
          v-model="searchQuery" 
          placeholder="搜索变量" 
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
        />
        
        <div v-if="loading" class="loading">
          <el-skeleton :rows="3" animated />
        </div>
        
        <div v-else-if="displayedVariables.length === 0" class="no-variables">
          <p>没有找到匹配的变量</p>
        </div>
        
        <div v-else class="variable-list">
          <div class="list-section" v-if="showGlobalSection && filteredGlobalVariables.length > 0">
            <div class="section-title">全局变量</div>
            <div 
              v-for="variable in filteredGlobalVariables" 
              :key="variable.id"
              class="variable-item"
              @click="selectVariable(variable)"
            >
              <div class="variable-name">${{ variable.name }}</div>
              <div class="variable-type">{{ getTypeText(variable.type) }}</div>
            </div>
          </div>
          
          <div class="list-section" v-if="showEventSection && filteredEventVariables.length > 0">
            <div class="section-title">事件变量</div>
            <div 
              v-for="variable in filteredEventVariables" 
              :key="variable.id"
              class="variable-item"
              @click="selectVariable(variable)"
            >
              <div class="variable-name">${{ variable.name }}</div>
              <div class="variable-type">{{ getTypeText(variable.type) }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { MagicStick as ElIconMagicStick } from '@element-plus/icons-vue'

const props = defineProps({
  eventId: {
    type: String,
    required: true
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['select'])
const store = useStore()

const popoverVisible = ref(false)
const searchQuery = ref('')
const loading = ref(false)
const activeTab = ref('all')

// 计算属性：所有可用变量
const allVariables = computed(() => store.state.allAvailableVariables)

// 计算属性：全局变量
const globalVariables = computed(() => 
  allVariables.value.filter(v => v.scope === 'global')
)

// 计算属性：事件局部变量
const eventVariables = computed(() => 
  allVariables.value.filter(v => v.scope === 'event')
)

// 计算属性：搜索过滤后的全局变量
const filteredGlobalVariables = computed(() => {
  if (!searchQuery.value) return globalVariables.value
  const query = searchQuery.value.toLowerCase()
  return globalVariables.value.filter(v => 
    v.name.toLowerCase().includes(query) || 
    (v.description && v.description.toLowerCase().includes(query))
  )
})

// 计算属性：搜索过滤后的事件局部变量
const filteredEventVariables = computed(() => {
  if (!searchQuery.value) return eventVariables.value
  const query = searchQuery.value.toLowerCase()
  return eventVariables.value.filter(v => 
    v.name.toLowerCase().includes(query) || 
    (v.description && v.description.toLowerCase().includes(query))
  )
})

// 计算属性：所有过滤后的变量
const filteredVariables = computed(() => [
  ...filteredGlobalVariables.value,
  ...filteredEventVariables.value
])

// 计算是否显示全局变量部分
const showGlobalSection = computed(() => 
  activeTab.value === 'all' || activeTab.value === 'global'
)

// 计算是否显示事件变量部分
const showEventSection = computed(() => 
  activeTab.value === 'all' || activeTab.value === 'event'
)

// 计算当前应该显示的变量列表
const displayedVariables = computed(() => {
  if (activeTab.value === 'all') return filteredVariables.value
  if (activeTab.value === 'global') return filteredGlobalVariables.value
  if (activeTab.value === 'event') return filteredEventVariables.value
  return []
})

// 获取变量类型显示文本
const getTypeText = (type) => {
  switch (type) {
    case 'string': return '字符串'
    case 'number': return '数字'
    case 'boolean': return '布尔值'
    case 'datetime': return '日期时间'
    case 'array': return '数组'
    case 'object': return '对象'
    default: return type
  }
}

// 加载事件可用变量
const loadAllVariables = async () => {
  if (!props.eventId) return
  
  loading.value = true
  try {
    await store.dispatch('fetchAllAvailableVariables', props.eventId)
  } catch (error) {
    console.error('获取变量失败:', error)
  } finally {
    loading.value = false
  }
}

// 选择变量
const selectVariable = (variable) => {
  emit('select', {
    name: variable.name,
    type: variable.type,
    scope: variable.scope
  })
  popoverVisible.value = false
}

// 监听事件ID变化
watch(() => props.eventId, (newId) => {
  if (newId) {
    loadAllVariables()
  }
})

onMounted(() => {
  if (props.eventId) {
    loadAllVariables()
  }
})
</script>

<style scoped>
.variable-button {
  margin-left: 8px;
}

.search-input {
  margin-bottom: 10px;
}

.popover-content {
  max-height: 300px;
  overflow-y: auto;
}

.variable-tabs {
  margin-bottom: 8px;
}

.loading,
.no-variables {
  padding: 10px;
  text-align: center;
  color: #909399;
}

.list-section {
  margin-bottom: 12px;
}

.section-title {
  padding: 5px 0;
  font-weight: bold;
  color: #606266;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 5px;
}

.variable-item {
  padding: 6px 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  border-radius: 4px;
}

.variable-item:hover {
  background-color: #f5f7fa;
}

.variable-name {
  font-weight: 500;
  color: #409eff;
}

.variable-type {
  font-size: 12px;
  color: #909399;
}
</style> 